package org.bing.engine.common.multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import org.bing.engine.utility.codec.SimpleObjectCodec;

public class MulticastClient {
    private static final SimpleObjectCodec codec = new SimpleObjectCodec();
    public static final int MAX_DATAGRAMPACKET_LENGTH = 1024 * 1;

    protected String multicastIp;
    protected InetAddress multicastAddress;
    protected int multicastPort;

    protected MulticastSocket multicastSocket;

    public MulticastClient() {
        try {
            multicastSocket = new MulticastSocket();
        } catch (IOException e) {
            throw new RuntimeException("Generate multicast client error!", e);
        }
    }

    public MulticastClient(String multicastIp, int multicastPort) {
        this.multicastPort = multicastPort;
        try {
            multicastAddress = InetAddress.getByName(multicastIp);
            multicastSocket = new MulticastSocket();
        } catch (IOException e) {
            throw new RuntimeException("Generate multicast client error!", e);
        }
    }

    public void send(Object obj) {
        String msg = obj instanceof String ? (String) obj : codec.encode(obj);
        if (msg.length() > MAX_DATAGRAMPACKET_LENGTH) {
            throw new RuntimeException("Datagrampacket length is over " + MAX_DATAGRAMPACKET_LENGTH);
        }
        byte[] msgBytes = msg.getBytes();
        try {
            if (multicastAddress == null) {
                multicastAddress = InetAddress.getByName(multicastIp);
            }
            DatagramPacket datagramPacket = new DatagramPacket(msgBytes, msgBytes.length, multicastAddress, multicastPort);
            multicastSocket.send(datagramPacket);
        } catch (IOException e) {
            throw new RuntimeException("Send datagrampacket error!", e);
        }
    }

    public String getMulticastIp() {
        return multicastIp;
    }

    public void setMulticastIp(String multicastIp) {
        this.multicastIp = multicastIp;
    }

    public int getMulticastPort() {
        return multicastPort;
    }

    public void setMulticastPort(int multicastPort) {
        this.multicastPort = multicastPort;
    }

    public static void main(String[] args) {
        try {
            // Create a datagram package and send it to the multicast
            // group at239.0.0.1, port 7892.
            MulticastClient mc = new MulticastClient("239.0.0.1", 7892);
            for (int i = 0; i < 50; i++) {
                mc.send("hello world!");
                Thread.sleep(200);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}